package com.kgc.xsConsumer.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kgc.basic.util.ResponseMsg;
import com.kgc.xs.pojo.SalesOrders;
import com.kgc.xs.pojo.SalesQuotes;
import com.kgc.xs.pojo.SalesReturn;
import com.kgc.xsConsumer.feign.ImportExportFeign;
import com.kgc.xsConsumer.feign.SalesOrdersFeign;
import com.kgc.xsConsumer.feign.SalesReturnFeign;
import com.kgc.xsConsumer.feign.XSWorkFlowFeign;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/SalesReturnController")
@CrossOrigin
public class SalesReturnController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SalesReturnFeign salesReturnFeign;

    @Autowired
    private XSWorkFlowFeign xsWorkFlowFeign;

    @Autowired
    private ImportExportFeign importExportFeign;


    @RequestMapping("/selectSalesReturnByPage")
    public ResponseMsg selectSalesReturnByPage(@RequestBody Map<String, Object> map) {
        logger.info("SalesReturnController selectSalesReturnByPage params {}",map.toString());
        ResponseMsg responseMsg = salesReturnFeign.selectSalesReturnByPage(map);
        logger.info("SalesReturnController selectSalesReturnByPage responseMsg {}",responseMsg.toString());
        return responseMsg;
    }


    @RequestMapping("/insertSalesReturn")
    public ResponseMsg insertSalesReturn(@RequestBody Map<String, Object> map ) {
        logger.info("SalesReturnController insertSalesReturn params {}",map.toString());
        ResponseMsg responseMsg = salesReturnFeign.insertSalesReturn(map);
        ObjectMapper mapper = new ObjectMapper();

        // 转换 SalesOrder 对象
        SalesReturn order = mapper.convertValue(
                map.get("salesReturn"),
                SalesReturn.class
        );

        Map<String,Object> variables = new HashMap<>();
        variables.put("code",order.getDocCode());//单据编号
        variables.put("type",order.getTypeId());//流程类型
        //创建一个流程实例
        xsWorkFlowFeign.startProcess(variables);
        logger.info("SalesReturnController insertSalesReturn responseMsg {}",responseMsg.toString());
        return responseMsg;
    }

    @RequestMapping("/deleteSalesReturn")
    public ResponseMsg deleteSalesReturn(@RequestBody Map<String, Object> map) {
        logger.info("SalesReturnController deleteSalesReturn params {}",map.toString());
        ResponseMsg responseMsg = salesReturnFeign.deleteSalesReturn(map);
        logger.info("SalesReturnController deleteSalesReturn responseMsg {}",responseMsg.toString());
        return responseMsg;
    }

    @RequestMapping("/updateSalesReturn")
    public  ResponseMsg updateSalesReturn(@RequestBody Map<String, Object> map) {
        logger.info("SalesReturnController updateSalesReturn params {}",map.toString());
        ResponseMsg responseMsg=salesReturnFeign.updateSalesReturn(map);
        logger.info("SalesReturnController updateSalesReturn responseMsg {}",responseMsg.toString());
        return responseMsg;
    }

    @RequestMapping("/checkSalesReturn")
    public ResponseMsg checkSalesReturn(@RequestBody Map<String, Object> map) {
        logger.info("SalesReturnController checkSalesReturn params {}",map.toString());
        ResponseMsg responseMsg=new ResponseMsg();
        Map<String,Object> variables = new HashMap<>();
        variables.put("code",(String) map.get("docCode"));//单据编号
        variables.put("checkManId",(Integer) map.get("checkManId"));//审批人
        variables.put("checkManName",(String) map.get("checkManName"));//审批人
        variables.put("checkComment",(String) map.get("checkComment"));//审批意见
        variables.put("checkDate",new Date());//审批时间
        variables.put("checkRes",(boolean)map.get("checkRes"));//审批结果
        com.kgc.activiti.util.ResponseMsg msg=  xsWorkFlowFeign.competeTask(variables);
        responseMsg.setCode(msg.getCode());
        responseMsg.setMsg(msg.getMsg());
        logger.info("SalesReturnController checkSalesReturn responseMsg {}",responseMsg.toString());
        return responseMsg;
    }

    @RequestMapping("/selectSalesReturnByCode")
    public ResponseMsg selectSalesReturnByCode(String docCode) {
        logger.info("SalesReturnController selectSalesReturnByCode params {}",docCode);
        ResponseMsg responseMsg=salesReturnFeign.selectSalesReturnByCode(docCode);
        logger.info("SalesReturnController selectSalesReturnByCode responseMsg {}",responseMsg.toString());
        return responseMsg;
    }

    @RequestMapping("/selectSalesReturnDetailByCode")
    public ResponseMsg selectSalesReturnDetailByCode(String xsReturnCode) {
        logger.info("SalesReturnController selectSalesReturnDetailByCode params {}",xsReturnCode);
        ResponseMsg responseMsg=salesReturnFeign.selectSalesReturnDetailByCode(xsReturnCode);
        logger.info("SalesReturnController selectSalesReturnDetailByCode responseMsg {}",responseMsg.toString());
        return responseMsg;
    }

    @RequestMapping(value = "/export")
    public void exportSalesInvoices(@RequestBody Map<String, Object> map, HttpServletResponse response) {
        logger.info("consumer SalesInvoiceController exportSalesInvoices params:{}", map);
        try {
            ResponseMsg responseMsg = importExportFeign.exportEntities(map, "com.kgc.xs.pojo.SalesReturn", "create_date desc");
            if ("200".equals(responseMsg.getCode())) {
                String base64Data = (String) responseMsg.getData();
                byte[] exportData = Base64.getDecoder().decode(base64Data);

                //设置响应头
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("UTF-8");
                String filename = URLEncoder.encode("销售退货单信息表.xlsx", "UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);

                response.getOutputStream().write(exportData);
            } else {
                logger.error("导出失败, msg: {}", responseMsg.getMsg());
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (IOException e) {
            logger.error("consumer SalesInvoiceController exportSalesInvoices is error", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }


    //下载模板
    @RequestMapping(value = "/template", method = RequestMethod.GET)
    public void downTemplate(HttpServletResponse response) {
        logger.info("consumer CustomerController downTemplate is start...");
        try {
            ResponseMsg responseMsg = importExportFeign.downLoadTemplate("com.kgc.xs.pojo.SalesReturn");
            if ("200".equals(responseMsg.getCode())) {
                String base64Data = (String) responseMsg.getData();
                byte[] templateData = Base64.getDecoder().decode(base64Data);   //解码

                //设置响应头
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("UTF-8");
                String filename = URLEncoder.encode("客户信息表.xlsx", "UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);

                response.getOutputStream().write(templateData);
            } else {
                logger.error("下载模板失败, status: {}", responseMsg.getMsg());
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (IOException e) {
            logger.error("consumer CustomerController downTemplate is error", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    //导入
    @RequestMapping(value = "/import", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseMsg importInfo(@RequestPart("file") MultipartFile file) {
        logger.info("consumer CustomerController importInfo fileName:{}", file.getOriginalFilename());
        return importExportFeign.importInfo(file, "com.kgc.xs.pojo.SalesReturn", "code", "");
    }




}
